<template>
  <div style="width: 100%;">
    <div class="header" style="width: 100%;background-color: white">
      <el-page-header content="资金计划支出" @back="goBack">
      </el-page-header>
      <el-divider></el-divider>
    </div>

    <div style="width: 90%;margin: 0 auto">
      <div style="width: 100%;">
        <span style="font-weight: 700;font-size: 20px">|基本信息</span>
      </div>
      <el-divider></el-divider>
      <el-form label-width="100px" style="width: 100%;">
        <el-container>
          <el-form-item label="填报日期：">
            <el-input v-model="expendFundPlanjbxx.fillingDate" readonly></el-input>
          </el-form-item>
          <el-form-item label="计划编号：">
            <el-input v-model="expendFundPlanjbxx.planId" readonly></el-input>
          </el-form-item>
        </el-container>
        <el-container>
          <el-form-item label="资金计划名称: ">
            <el-input v-model="expendFundPlanjbxx.fundplanName" ></el-input>
          </el-form-item>
          <el-form-item label="项目选择：">
            <el-input v-model="expendFundPlanjbxx.projectName" readonly
                      @focus="projectDialogVisible=true"></el-input>

          </el-form-item>
        </el-container>

        <el-container>
          <el-form-item label="计划月份：">
            <el-date-picker
                v-model="expendFundPlanjbxx.planIn"
                :picker-options="pickerOptionsYearMonth"
                format="yyyy年M月"
                placeholder="选择日期"
                type="month">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="申请金额：">
            <el-input v-model="expendFundPlanjbxx.applyForMoney" @input="money"></el-input>
          </el-form-item>
        </el-container>
        <el-container>
          <el-form-item label="金额大写：">
            <el-input v-model="expendFundPlanjbxx.moneyCapitalization" readonly></el-input>
          </el-form-item>
          <el-form-item label="填报人：">
            <el-input v-model="expendFundPlanjbxx.filledBy" readonly></el-input>
          </el-form-item>
        </el-container>
        <el-container>
          <el-form-item label="备注：">
            <el-input v-model="expendFundPlanjbxx.mainContent" style="width: 1110px;"
                      type="textarea"></el-input>
          </el-form-item>
        </el-container>
      </el-form>
    </div>

        <multi-file-upload
            style="width: 90%;margin: 20px auto"
            title="附件"
            action="http://localhost/uploads"
            :params="{folder: 'tenderPurchasePlan'}"
            :headers="{token: token}"
            :show-button="!checkRoute"
            @uploadSuccess="handleUploadSuccess"
            :parent-file-list="fileList"
        ></multi-file-upload>

    <div style="width: 90%;margin: 30px auto">
      <div style="width: 100%;">
        <div style="font-weight: 700;font-size: 20px;display: flex">
          <div>|资金计划明细</div>
          <div style="margin-left: 30px">
            <el-button v-if="!checkRoute" size="mini" type="primary" @click="handleAddRow">增行</el-button>
          </div>
        </div>
      </div>
      <el-divider></el-divider>
      <el-table :data="expendFundPlanmx">
        <el-table-column prop="index" v-if="false"></el-table-column>
        <el-table-column prop="mateId" v-if="false"></el-table-column>
        <el-table-column label="费用类型" prop="useDept"  >
          <template slot-scope="scope">
<!--            <el-input v-model="scope.row.expenseTypeID" style="width: 300px" ></el-input>-->
            <el-select
                v-model="scope.row.expenseTypeId"
                placeholder="请选择费用类型"
                style="width: 300px"

            >
              <el-option
                  :label="item.expenseType"
                  v-for="item in costType"
                  :key="item.id"
                  :value="item.id"

              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="计划金额" prop="buyTime">
          <template slot-scope="scope">
            <el-input v-model="scope.row.planMoney" type="number"   @change="handleEdit2(scope.$index, scope.row)"
                      @blur="handleEdit2(scope.$index, scope.row)"    @input="handleEdit2(scope.$index, scope.row)" style="width: 300px"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="providerName">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remarks" style="width: 300px"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button v-if="!checkRoute" type="danger" @click="handleRemoveRow(scope.row)">删行</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div v-if="show">
        <label for="" style="display: inline-block; width: 50px">合计: </label>
        <el-input style="width: 200px" v-model="input1"></el-input>
        <label
            for=""
            style="display: inline-block; width: 90px; margin-left: 30px; "
        >金额大写:
        </label>
        <el-input style="width: 350px" v-model="input2"></el-input>
      </div>
    </div>
    <el-divider></el-divider>
    <div style="width: 100%;margin-left: 90px">
      <el-button type="primary" @click="handleSubmit" v-if="!checkRoute">确认提交</el-button>
    </div>

    <el-dialog
        title="项目选择"
        :visible.sync="projectDialogVisible"
        width="70%">
      <project-info-list @row="handleSetProject" v-if="projectDialogVisible"></project-info-list>
    </el-dialog>

  </div>
</template>


<script>
import { HandleNumFormat } from "../../../model/sy/HandleNumFormat.js";
import {AttachemenInfoService} from "../../../model/gs/AttachemenInfoService";
import {ZiJinZhiChuJiHua} from "../../../model/xz/ZiJinZhiChuJiHua";
import {ZiJinZhiChuJiHuaBaoCun} from "../../../model/xz/ZiJinZhiChuJiHuaBaoCun";
import {ZiJinZhiChuJiHuamx} from "../../../model/xz/ZiJinZhiChuJiHuamx";
import {DateUtil} from "@/model/common/DateUtil";
const ProjectInfoList = () => import('../../common/projectInfo/ProjectInfoList.vue')
const attachemenInfoService = AttachemenInfoService.getInstance();
const ziJinZhiChuJiHua = ZiJinZhiChuJiHua.getInstance();
const ziJinZhiChuJiHuaBaoCun = ZiJinZhiChuJiHuaBaoCun.getInstance();
const ziJinZhiChuJiHuamx = ZiJinZhiChuJiHuamx.getInstance();
export default {
  name: "expendFundPlan",
  data() {
    return {
      pickerOptionsYearMonth: this.banTime(),
      expendFundPlanjbxx: {
        planId:'',
        fillingDate: DateUtil.today(),
        filledBy: sessionStorage.getItem('realName'),
      },
      fileList: [],
      projectDialogVisible: false,
      expendFundPlanmx:[],
      costType:[],
      input1:"",
      input2:"",
      show:false,

    }
  },
  methods: {

    banTime() {
      return {
        disabledDate(time) {
          const date = new Date()
          const year = date.getFullYear()
          let month = date.getMonth() + 1
          if (month >= 1 && month <= 9) {
            month = '0' + month
          }
          const currentDate = year.toString() + month.toString()
          const timeYear = time.getFullYear()
          let timeMonth = time.getMonth() + 1
          if (timeMonth >= 1 && timeMonth <= 9) {
            timeMonth = '0' + timeMonth
          }
          const timeDate = timeYear.toString() + timeMonth.toString()
          console.log(time)
          return currentDate >= timeDate
        }
      }
    },
    checkTime(i) {
      if (i < 10) {
        i = '0' + i
      }
      return i
    },
    goBack() {
      history.back()
    },
    //转换器
    toChies(values) {//形参
      let len = values.length//统计出长度
      let arr = [];

      let chin_list = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']//所有的数值对应的汉字

      let chin_lisp = ['仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾']//进制

      for (let i = 0; i < len; i++) {
        arr.push(parseInt(values[i]));		//输入的数据按下标存进去   存进去的只是数字
        arr[i] = chin_list[arr[i]]			//是根据我们输入的输入的数字，对应着我们的chin_list这个数组
      }//123['壹','佰','贰','拾','叁']

      for (let i = len - 1, j = 1; i > 0; i--) {//i =2	1		//倒序		为了添加进制，方便我们去观看
        arr.splice(i, 0, chin_lisp[chin_lisp.length - j++])	//j=2
      }
      console.log(arr)

      arr = arr.join('')
      if (len >= 1) {
        arr += '元整'
      }
      return arr
    },
    // CurrentTime() {
    //   var date = new Date();
    //   // 获取当前月份
    //   var nowMonth = date.getMonth() + 1;
    // // 获取当前是几号
    //   var strDate = date.getDate();
    // // 添加分隔符“-”
    //   var seperator = "-";
    // // 对月份进行处理，1-9月在前面添加一个“0”
    //   if (nowMonth >= 1 && nowMonth <= 9) {
    //     nowMonth = "0" + nowMonth;
    //   }
    // // 对月份进行处理，1-9号在前面添加一个“0”
    //   if (strDate >= 0 && strDate <= 9) {
    //     strDate = "0" + strDate;
    //   }
    // // 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
    //   var nowDate = date.getFullYear() + seperator + nowMonth + seperator + strDate;
    //   this.expendFundPlanjbxx.fillingDate = nowDate;
    //
    // },

    //金额转换
    money() {
      var money = this.expendFundPlanjbxx.applyForMoney;
      var Maxmoney = this.toChies(money);
      console.log(Maxmoney)
      this.expendFundPlanjbxx.moneyCapitalization = Maxmoney
    },
    handleEdit2() {
      this.show=true;
      // 循环给合计赋值
      console.log(this.expendFundPlanmx);
      const val = this.expendFundPlanmx.reduce(
          (prev, curr) => Number(prev) + Number(curr.planMoney),
          0
      );
      this.input1 = HandleNumFormat.numFormat(val);
      this.input2 = HandleNumFormat.handleAmountUpper(
          parseFloat(val).toFixed(2)
      );
    },
    //文件上传
    handleUploadSuccess(ids){
      console.log(ids)
      this.expendFundPlanjbxx.attachemenIds = ids
    },
    handleSetProject(row) {
      this.expendFundPlanjbxx.projectName = row.projectName
      this.projectDialogVisible = false
    },
    //获取最大计划编号
    getMaxCode() {
      ziJinZhiChuJiHuaBaoCun.getMaxCode().then(response => {
        if (response.data.code === 0) {
          console.log(response.data.data)
          this.expendFundPlanjbxx.planId = response.data.data
          console.log(this.expendFundPlanjbxx.planId);
        }
      })
    },
    //根据计划编号查询基本信息
    getPlanById(id) {
      ziJinZhiChuJiHuaBaoCun.getById(id).then(response => {
        if (response.data.code === 0) {
          this.expendFundPlanjbxx = response.data.data
        }
      })
    },
    //根据计划编号查询明细
    getDetailList(planId) {
      console.log(planId)
      ziJinZhiChuJiHuamx.getByPlan(planId).then(response => {
        if (response.data.code === 0) {
          this.expendFundPlanmx = response.data.data
          this.handleEdit2();
        }
      })
    },
    getFileList(id) {
      attachemenInfoService.getById(id).then(response => {
        if (response.data.code === 0) {
          response.data.data.forEach(item => {
            this.fileList.push({
              fileName: item.fileName,
              uploadPerson: this.expendFundPlanjbxx.planEditor,
              uploadDate: item.uploadDate,
              filePath: item.filePath
            })
          })
        }
      })
    },
    handleAddRow() {
      this.expendFundPlanmx.push({
        planId: this.expendFundPlanjbxx.planId,

        expenseTypeID:'',
        planMoney:'',
        remarks:'',
      })
    },
    handleRemoveRow(row) {
      this.expendFundPlanmx.splice(row.index, 1);
      this.handleEdit2();

    },
    //费用类型
    expenseTypeList(){
      ziJinZhiChuJiHua.getexpenseType().then((response) => {
        console.log(response);
        this.costType = response.data.data;
      });

    },
    handleSubmit() {

      if(this.expendFundPlanjbxx.fundplanName=='' || this.expendFundPlanjbxx.fundplanName==null ){
        this.$message.error("请输入资金计划名称!")
        return;
      }
      if(this.expendFundPlanjbxx.projectName=='' || this.expendFundPlanjbxx.projectName==null ){
        this.$message.error("请选择项目名称!")
        return;
      }

      if(this.expendFundPlanjbxx.planIn=='' || this.expendFundPlanjbxx.planIn==null ){
        this.$message.error("请选择计划月份!")
        return;
      }


      if(this.expendFundPlanjbxx.applyForMoney=='' || this.expendFundPlanjbxx.applyForMoney==null ){
        this.$message.error("请输入申请金额!")
        return;
      }

      if(this.expendFundPlanjbxx.applyForMoney<0){
        this.$message.error("请输入正确的金额!")
        return;
      }




      if(this.expendFundPlanmx[0].expenseTypeId =='' || this.expendFundPlanmx[0].expenseTypeId ==null ){
        this.$message.error("请选择费用类型!")
        return;
      }
      this.expendFundPlanmx.forEach(i=>{
        if(i.planMoney=='' || i.planMoney ==null ){
          this.$message.error("请输入计划金额!")
          return;
        }
        if(i.planMoney<0){
          this.$message.error("请输入正确金额!")
          return;
        }
      })



      console.log(this.expendFundPlanmx,this.expendFundPlanjbxx)
      ziJinZhiChuJiHuaBaoCun.save(this.expendFundPlanjbxx, this.expendFundPlanmx).then(response => {
        if (response.data.code === 0) {
          this.$message.success({
            message: '保存成功',
            duration: 1000
          })
          this.$router.push({
            path: '/expendFundPlanlist'
          })
        }
      })
    },

  },

  computed: {
    token: {
      get() {
        return this.$store.state.token
      }
    },
    checkRoute(){
      return Object.keys(this.$route.params).length != 0
    }
  },
  created() {
    if (Object.keys(this.$route.params).length == 0) {
      this.getMaxCode();
      this.expenseTypeList();
    }else {
      const row = this.$route.params.row
      console.log(row);
      this.expenseTypeList();
      // this.CurrentTime();
      this.getPlanById(row.id);
      this.getDetailList(row.planId)
      this.getFileList(row.attachemenIds)
      this.handleEdit2();
    }


  },
  components: {
    ProjectInfoList,

  }


}
</script>

<style scoped>

.el-input {
  width: 400px;
}

</style>